<!-- src/views/LoginPage.vue -->
<template>
  <div class="login-page">
    <h2>登录</h2>
    <form @submit.prevent="handleLogin">
      <div>
        <label for="username">用户名:</label>
        <input type="text" id="username" v-model="username" required />
      </div>
      <div>
        <label for="password">密码:</label>
        <input type="password" id="password" v-model="password" required />
      </div>
      <button type="submit">登录</button>
    </form>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import request from '@/request/request';
import { ElMessage } from 'element-plus'; // 引入 ElMessage

const router = useRouter();

const username = ref('');
const password = ref('');

async function handleLogin() {
  try {
    const response = await request.post('/auth/login', {
      username: username.value,
      password: password.value
    });
    console.log('登录成功:', response);
    localStorage.setItem('token', response.data.token);
    localStorage.setItem('username', response.data.username);
    // 重定向到首页
    router.push('/list');
  } catch (error) {
    console.error('登录失败:', error);
    // 显示错误提示框
    ElMessage.error('登录失败，请检查用户名和密码');
  }
}
</script>

<style scoped>
.login-page {
  max-width: 300px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
form div {
  margin-bottom: 15px;
}
label {
  display: block;
  margin-bottom: 5px;
}
input {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
}
button {
  width: 100%;
  padding: 10px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
button:hover {
  background-color: #3eaf7c;
}
</style>
